<template>
  <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
    <el-form-item
      :label="$t('menu.profile.field.original_password')"
      prop="oldPassword"
    >
      <el-input
        v-model="formData.oldPassword"
        type="password"
        show-password
        autocomplete="current-password"
      />
    </el-form-item>
    <el-form-item
      :label="$t('menu.profile.field.new_password')"
      prop="newPassword"
    >
      <el-input
        v-model="formData.newPassword"
        type="password"
        show-password
        autocomplete="new-password"
      />
    </el-form-item>
    <el-form-item
      :label="$t('menu.profile.field.confirm_password')"
      prop="confirmPassword"
    >
      <el-input
        v-model="formData.confirmPassword"
        type="password"
        show-password
        autocomplete="new-password"
      />
    </el-form-item>
  </el-form>
</template>

<script setup>
import API from '@/api/admin/profile';
import { smartTranslate as $t, transPlaceholder as $p } from '@/lang';

const emit = defineEmits(['submit-success', 'submit-cancel']);

const formRef = ref(null);
const formData = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
});

const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error($t('menu.profile.validate.confirm_password')));
  } else if (value !== formData.newPassword) {
    callback(new Error($t('menu.profile.validate.not_match')));
  } else {
    callback();
  }
};

const rules = {
  oldPassword: [
    {
      required: true,
      message: $t('menu.profile.validate.original_password'),
      trigger: 'blur',
    },
  ],
  newPassword: [
    {
      required: true,
      message: $t('menu.profile.validate.new_password'),
      trigger: 'blur',
    },
    {
      min: 6,
      message: $t('common.message.validate.min', {
        field: $t('menu.profile.field.new_password'),
        min: 6,
      }),
      trigger: 'blur',
    },
  ],
  confirmPassword: [
    {
      required: true,
      validator: validateConfirmPassword,
      trigger: 'blur',
    },
  ],
};

const submitForm = async () => {
  try {
    const valid = await formRef.value.validate();
    if (valid) {
      const loginData = { ...formData };
      await API.changePassword(loginData);
      ElMessageBox.alert(
        $t('common.message.success.general', {
          action: $t('menu.profile.security.change_password'),
        }),
        $t('common.title.notice'),
        { type: 'success' },
      );
      emit('submit-success');
    }
  } catch (error) {
    console.error('密码修改失败:', error);
  }
};

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  // 清空表单数据
  formData.oldPassword = '';
  formData.newPassword = '';
  formData.confirmPassword = '';
};

defineExpose({
  submitForm,
  resetForm,
});
</script>
